package com.ca.ridersclubapplication.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;

import com.ca.ridersclubapplication.MainActivity;
import com.ca.ridersclubapplication.R;
import com.ca.ridersclubapplication.data.DataHandler;
import com.ca.ridersclubapplication.data.bean.BannerInfo;
import com.ca.ridersclubapplication.data.bean.MiniClubInfo;
import com.ca.ridersclubapplication.request.AfterExecutor;
import com.ca.ridersclubapplication.request.ClubRequester;
import com.ca.ridersclubapplication.request.dto.ClubDto;
import com.ca.ridersclubapplication.request.dto.PaperCardDto;
import com.ca.ridersclubapplication.request.FileRequester;
import com.ca.ridersclubapplication.request.PaperRequester;
import com.ca.ridersclubapplication.request.dto.Result;
import com.ca.ridersclubapplication.view.bar.MainTitleBar;
import com.ca.ridersclubapplication.view.list.PaperCardListView;

import java.util.ArrayList;
import java.util.List;

public class MainFragment extends Fragment implements RefreshableFragment {

    private static int y = 0;

    private final ConstraintLayout titleCL;
    private final MainTitleBar titleBar;

    public PaperCardListView paperCardListView;


    //  关注的车友圈列表
    private List<MiniClubInfo> miniClubInfoList = new ArrayList<>();

    //  广告Banner图片列表
    List<BannerInfo> bannerInfoList = new ArrayList<>();

    //  是否开启请求标志
    private static boolean canRequest = true;
    private ProgressBar progressBar;

    //  请求数据追加结尾或头部标志（下拉刷新 或 滑动到底部刷新）
    private static boolean appendToTop = false;

    public MainFragment(ConstraintLayout titleCL, MainTitleBar titleBar) {
        this.titleCL = titleCL;
        this.titleBar = titleBar;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_main_layout, container, false);

        initView(view);

        initListener();

        loadData();

        return view;
    }

    private void initView(View view) {

        //  初始化文章列表视图
        paperCardListView = view.findViewById(R.id.lv_paper);
        paperCardListView.adapter.setActivity(getActivity());

        //  进度条
        progressBar = view.findViewById(R.id.bar_progress);
    }

    private void initListener() {

        //  设置文章列表滑动监听
        //  当滑动到一定高度时，改变标题栏 亮色 或 暗色
        paperCardListView.rv.addOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                y += dy;
                int h = (int) (paperCardListView.getMeasuredWidth() * (5.5/ 8));
                //  768 or h，当滑动距离大于该值时，设置标题栏样式（亮色、暗色），以及底部首页按钮功能（回到顶部）
                if (y < h) {
                    titleCL.setBackgroundColor(getResources().getColor(R.color.transparent));
                    titleBar.light();
                    MainActivity activity = (MainActivity) getActivity();
                    if (activity != null) {
                        activity.showToTopIcon(false);
                        MainActivity.canToTop(false);
                    }
                }
                else {
                    titleCL.setBackgroundColor(getResources().getColor(R.color.base_background));
                    titleBar.dark();
                    MainActivity activity = (MainActivity) getActivity();
                    if (activity != null) {
                        activity.showToTopIcon(true);
                        MainActivity.canToTop(true);
                    }
                }

                //  滑动到底部则加载新的文章数据
                if (!paperCardListView.rv.canScrollVertically(1)) {
                    requestPaper(false);
                }
            }
        });
    }

    private void loadData() {

        //  请求广告卡片 和 广场列表数据
        listFollowClub();
        listBanner();

        //  首次请求文章数据
        requestPaper(false);
    }

    //  请求关注车友圈列表
    private void listFollowClub() {
        if (DataHandler.isLogin(getActivity())) {
            ClubRequester.listFollowClub(getActivity(), DataHandler.getToken(getActivity()).getId(), new AfterExecutor<List<ClubDto>>() {
                @Override
                public void execute(Result<List<ClubDto>> result) {
                    if (result.isSuccess()) {
                        //  请求成功，设置关注的车友圈卡片列表
                        List<ClubDto> data = result.getData();
                        miniClubInfoList = new ArrayList<>();
                        for (ClubDto dto : data) {
                            miniClubInfoList.add(new MiniClubInfo(
                                    dto.getId(),
                                    FileRequester.CLUB_IMAGE_1_1_BASE_URL + dto.getId(),
                                    dto.getName()
                            ));
                        }

                        paperCardListView.adapter.setMainHeader(bannerInfoList, miniClubInfoList);
                    }
                }
            });
        }
    }

    //  请求广告Banner列表
    private void listBanner() {
        ClubRequester.listBannerClubId(getActivity(), new AfterExecutor<List<Long>>() {
            @Override
            public void execute(Result<List<Long>> result) {
                if (result.isSuccess()) {
                    List<Long> data = result.getData();
                    bannerInfoList = new ArrayList<>();
                    for (Long d : data) {
                        bannerInfoList.add(new BannerInfo(d, FileRequester.CLUB_IMAGE_16_9_BASE_URL + d));
                    }

                    paperCardListView.adapter.setMainHeader(bannerInfoList, miniClubInfoList);
                }
            }
        });
    }

    public static int getY() {
        return y;
    }

    @Override
    public void refresh() {
        //  加载文章数据
        requestPaper(true);
    }

    private synchronized void requestPaper(boolean toTop) {
        if (canRequest) {
            canRequest = false;
            appendToTop = toTop;
            //  显示加载动画
            progressBar.setVisibility(toTop ? View.GONE : View.VISIBLE);
            PaperRequester.listPapers(getActivity(), new AfterExecutor<List<PaperCardDto>>() {
                @Override
                public void execute(Result<List<PaperCardDto>> result) {

                    if (!result.isSuccess()) {
                        return;
                    }

                    List<PaperCardDto> data = result.getData();
                    //  判断追加位置（头部或尾部）
                    if (appendToTop) {
                        paperCardListView.appendListToTop(data);

                        //  停止下拉刷新动画
                        MainActivity activity = (MainActivity) getActivity();
                        if (activity != null) {
                            activity.stopRefreshing();
                        }
                    }
                    else {
                        paperCardListView.appendList(data);
                    }

                    //  数据设置完毕后，开启允许请求
                    canRequest = true;

                    //  关闭加载动画
                    progressBar.setVisibility(View.GONE);
                }
            });
        }
        else {
            MainActivity activity = (MainActivity) getActivity();
            if (activity != null) {
                activity.stopRefreshing();
            }
        }
    }

    public void goToTop() {
        paperCardListView.rv.smoothScrollToPosition(0);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }
}
